package com.bookstore.admin.product.handler;


import com.bookstore.admin.product.service.AdminProductService;
import com.bookstore.commons.beans.*;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.apache.ibatis.annotations.Insert;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@Controller
@RequestMapping("/admin/product")
public class AdminProductHandler {

    @Autowired
    AdminProductService adminProductService;

    //伪用户登录
    @RequestMapping("/login")
    public String login(String logonName, String logonPwd, Model model){
        Integer row = adminProductService.findUser(logonName,logonPwd);
        if (row != null){
            return "/admin/login/home.jsp";
        }else {
            model.addAttribute("admin_error","用户名或密码错误");
            return "/admin/login/login.jsp";
        }
    }

    //点击左边的商品管理
    @RequestMapping("/listProduct")
    public String listProduct(Model model){
        List<Product> list = adminProductService.findProductList();
        model.addAttribute("ps",list);
        return "/admin/products/list.jsp";
    }

    //商品管理里的 编辑
    @RequestMapping("/findProductById")
    public String findProductById(Model model,String id){
        Product p = adminProductService.findProductById(id);
        model.addAttribute("p",p);
        return "/admin/products/edit.jsp";
    }

    //提交的编辑
    @RequestMapping("/editProduct")
    public String editProduct(Product product){
        System.out.println("编辑提交的数据:"+product);
        int row = adminProductService.editProduct(product);
        return "redirect:/admin/product/listProduct";
    }

    //商品管理中的删除
    @RequestMapping("/deleteProduct")
    public String deleteProduct(Model model,String id){
        int row = adminProductService.deleteProduct(id);
        return "redirect:/admin/product/listProduct";
    }

    //按条件查询  /////编号id  类别category 商品名称name      价格区间minprice///maxprice
    @RequestMapping("/findProductByManyCondition")
    public String findProductByManyCondition(Product product,Double minprice,Double maxprice,Model model){
//某字段 between 最小值 and 最大值；
        List<Product> products = adminProductService.findProductByManyCondition(product,minprice,maxprice);
        for (Product p: products){
            System.out.println(p);
        }
        model.addAttribute("ps",products);  //商品信息
        return "/admin/products/list.jsp";
    }


    @RequestMapping("/download")
    public void download(String year, String month, HttpServletResponse response, HttpServletRequest request) throws IOException {
        System.out.println(year+month);
        List<ProductList> plist = adminProductService.findProductSalList(year,month);
        for (ProductList pl:plist){
            System.out.println(pl);
        }

        //定义下载的Excel表的名称
        String filename = year + "年" + month + "月销售榜单";
        //工作表的名称
        String sheetName = month + "月销售榜单";
        //文件头
        String titleName = year + "年" + month + "月销售榜单";
        //列名
        String[] columName = {"商品名称","商品销量"};

        //    行 列
        String[][] dataList = new String[plist.size()][2];
        for (int i=0;i<plist.size();i++){
            dataList[i][0] = plist.get(i).getName();
            dataList[i][1] = plist.get(i).getSalnum();
        }

        //创建excle文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建工作表
        HSSFSheet sheet = wb.createSheet(sheetName);
        //创建sheel的第一行
        HSSFRow row1 = sheet.createRow(0);
        //创建第一行的第一个单元格
        HSSFCell cell = row1.createCell(0);
        //合并第一行的两个单元格  起始行 终止行 起始列  终止列
        sheet.addMergedRegion(new CellRangeAddress(0,0,0,1));
        //赋值
        cell.setCellValue(titleName);

        //创建第二行
        HSSFRow row = sheet.createRow(1);
        for (int i=0;i<2;i++){
            row.createCell(i).setCellValue(columName[i]);   //columName数组
        }

        //插入数据
        for (int i=0; i<dataList.length; i++){
            row = sheet.createRow(i+2);   //从第三行开始插入
            for(int j=0;j<2; j++){      //每行插入两个
                row.createCell(j).setCellValue(dataList[i][j]);
            }
        }

        //文件全名
        String fileName = filename + ".xls";
        //内容类型
        response.setContentType("application/ms-excel;charset=UTF-8");
        //作为附件响应回去
        response.setHeader("content-Disposition","attachment;filename="+processFileName(request,fileName));
        OutputStream out = response.getOutputStream();
        wb.write(out);
    }


    //解决乱码问题
    public String processFileName(HttpServletRequest request,String fileName){
        String codefilename = null;
        try{
            String agent = request.getHeader("USER-AGENT");
            if(null != agent && -1 != agent.indexOf("MSIE") || null != agent && -1 != agent.indexOf("Trident")){
                String name = java.net.URLEncoder.encode(fileName,"UTF8");
                codefilename = name;
            }else if (null != agent && -1 != agent.indexOf("Mozilla")){
                codefilename = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return codefilename;
    }


    //添加商品   addProduct
    @RequestMapping("/addProduct")
    public String addProduct(Product product,Model model){
        System.out.println(product);
        List<Product> list = adminProductService.findProductList();
        Product p = list.get(list.size()-1);
        Integer a = Integer.parseInt(p.getId())+1;
        product.setId(a.toString());
        System.out.println("pppppppppp"+product);
        int row = adminProductService.addProduct(product);
        return "redirect:/admin/product/listProduct";
    }

//======================================================================================================================
    //订单管理findOrders
    @RequestMapping("/findOrders")
    public String findOrders(Order order,Model model){
        List<Order> orders = adminProductService.findOrderList(order);
        for (Order o: orders){
            System.out.println(o);
        }
        model.addAttribute("orders",orders);
        return "/admin/orders/list.jsp";
    }


    //查看订单详细信息findOrderById
    @RequestMapping("/findOrderById")
    public String findOrderById(String id,Model model){
        List<Orderitem> items = adminProductService.findOrderItemById(id);
        for (Orderitem o:items){
            System.out.println(o);
        }
        model.addAttribute("items",items);
        return "/admin/orders/view.jsp";
    }

    //公告管理 ListNotice
    @RequestMapping("/ListNotice")
    public String ListNotice(Model model){
        List<Notice> notices = adminProductService.findNotice();
        for (Notice n:notices){
            System.out.println(n);
        }
        model.addAttribute("notices",notices);
        return "/admin/notices/list.jsp";
    }

    //公告 编辑  FindByIdNoticeServlet
    @RequestMapping("/FindByIdNoticeServlet")
    public String FindByIdNoticeServlet(Integer id,Model model){
        Notice n = adminProductService.FindByIdNoticeServlet(id);
        model.addAttribute("n",n);
        return "/admin/notices/edit.jsp";
    }

    //提交公告编辑EditNoticeServlet
    @RequestMapping("/EditNoticeServlet")
    public String EditNoticeServlet(Notice notice){
        int row= adminProductService.EditNoticeServlet(notice);
        return "redirect:/admin/product/ListNotice";
    }

    //删除公告
    @RequestMapping("/DeleteNoticeServlet")
    public String DeleteNoticeServlet(Integer id){
        int row = adminProductService.DeleteNoticeServlet(id);
        return "redirect:/admin/product/ListNotice";
    }

    //添加公告
    @RequestMapping("/AddNoticeServlet")
    public String AddNoticeServlet(Notice notice){
        int row = adminProductService.AddNoticeServlet(notice);
        return "redirect:/admin/product/ListNotice";
    }

    //退出
    @RequestMapping("/logout")
    public String logout(){
        return "/admin/login/login.jsp";
    }
}
